package com.cms.recursoshumanos.ui.catalogo.carrito;

import com.cms.recursoshumanos.cache.CarritoCompraCache;
import com.cms.recursoshumanos.cache.UserInfoCache;
import com.cms.recursoshumanos.component.ArticuloCarritoListButtonField;
import com.cms.recursoshumanos.constant.Constant;
import com.cms.recursoshumanos.container.ForegroundManager;
import com.cms.recursoshumanos.container.LinedGridFieldManager;
import com.cms.recursoshumanos.container.ListStyleButtonSetScrollManager;
import com.cms.recursoshumanos.container.SearchBarManager;
import com.cms.recursoshumanos.container.TwoColumnFieldManager;
import com.cms.recursoshumanos.engine.ScreenEngine;
import com.cms.recursoshumanos.handler.CarritoCompraScreenHandler;
import com.cms.recursoshumanos.object.ArticuloCarrito;
import com.cms.recursoshumanos.object.list.ListaArticuloCarrito;
import com.cms.recursoshumanos.popup.ShowDialogAlert;
//import com.cms.recursoshumanos.utilities.Utileria;


import com.cms.recursoshumanos.ui.RecursosHumanosScreen;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.GridFieldManager;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Border;
import net.rim.device.api.ui.decor.BorderFactory;



/**
 * @author Francisco Trompiz
 *
 * Corporate Mobile Solutions. 2013
 */

public class CarritoCompraScreen extends RecursosHumanosScreen implements FieldChangeListener 
{

	int cantidadWidth = getFont().getAdvance("00000");
	int precioWidth = getFont().getAdvance("0000000.00");
	int nombreWidth = ((Display.getWidth()*71)/100)- cantidadWidth - precioWidth;
	XYEdges margin = new XYEdges(2, 2, 2, 2);
	int [] intWidth = {nombreWidth+2,cantidadWidth,precioWidth,0};

	
	SearchBarManager sbm;
	ListStyleButtonSetScrollManager buttonSet;
	VerticalFieldManager vfm;
	HorizontalFieldManager hfm;
	
	TwoColumnFieldManager /*tcfm_pantalla,*/ tcfm_monto, tcfm_lista_articulo;
	GridFieldManager gfm;
	LabelField lblMontoCarrito,lblVacio;
	Border elBorder_Inicio = BorderFactory.createSimpleBorder(new  XYEdges(1, 1, 0, 1));
	Border elBorder_Final = BorderFactory.createSimpleBorder(new  XYEdges(0, 1, 0, 1));
	Border elBorder_Medio = BorderFactory.createSimpleBorder(new  XYEdges(0, 1, 0, 1));

	private static CarritoCompraScreen instance = null;
	
	private ListaArticuloCarrito lista_articulo;
	
	public static CarritoCompraScreen getInstance(ListaArticuloCarrito listado)
	{
		if(instance == null)
    	{
    		instance = new CarritoCompraScreen(listado);
    	}
		else
		{
			instance.lista_articulo = listado;
			instance.reset();
		}
		
    	return instance;
    }
	
	
	
    private ForegroundManager _foreground;
    
	public CarritoCompraScreen(ListaArticuloCarrito listado) 
	{
		super( NO_VERTICAL_SCROLL | USE_ALL_HEIGHT );
	  	
		lista_articulo = listado;	
		
		setComponents();
	}
	public void modificar_cantidad_articulo()
	{
		Field elField = buttonSet.getFieldWithFocus();
		if(elField instanceof LinedGridFieldManager )
		{
			ArticuloCarrito el_Articulo = ((LinedGridFieldManager)elField).getArticuloCarrito();
			ScreenEngine.getInstance().goEditCarritopopUp(el_Articulo,CarritoCompraScreen.instance);
		}
	}
	public void procesar_solicitud_compra()
	{
		CarritoCompraScreenHandler handler = new CarritoCompraScreenHandler(this);
		handler.procesarSolicitudCompra(UserInfoCache.getInstance().getUsuario().getNombre_Usuario(), 
				UserInfoCache.getInstance().getUsuario().getPassword());
	}
	protected void makeMenu(Menu menu, int instance) 
	{
		MenuItem procesarButton = new MenuItem("Procesar Solicitud de Compra", 0, 0) {
			public void run() 
			{
				procesar_solicitud_compra();
			}
		};
		MenuItem modificarButton = new MenuItem("Modificar Cantidad", 0, 0) 
        {
			public void run() 
			{
				modificar_cantidad_articulo();
			}
		};
		// Refresh...
		MenuItem refreshButton = new MenuItem("Refresh", 0, 0) {
			public void run() 
			{
				reset();
			}
		};
		menu.add(procesarButton);
		menu.add(modificarButton);
		menu.add(refreshButton);
		super.makeMenu(menu, instance);
	}
	
	public void reset() 
	{
		
		vfm.deleteAll();
		buttonSet.deleteAll();
		pintarMonto();
		//loading = false;
		try 
		{
			if(lista_articulo.cantElementListaArticulo() > 0) 
			{
				pintarListaArticuloCarrito();
			}
			else
			{
				pintarVacio();
			}
		} 
		catch (Exception e) 
		{
			ShowDialogAlert alert = new ShowDialogAlert("Exception in delete fields...");
			alert.run();
		}
		//pintarComponents();

	}
	
	public void setComponents() 
	{
		
		setTitle("Carrito de Compras");
		vfm = new VerticalFieldManager( Field.FIELD_HCENTER | VerticalFieldManager.NON_FOCUSABLE );
		_foreground = new ForegroundManager(NO_VERTICAL_SCROLL);
		//_foreground.setMargin( 10, 10, 10, 10 );
		_foreground.setPadding( 6, 6, 6, 6 );
		vfm.setPadding(10, 0, 0, 0);	
		
		/*tcfm_pantalla = new TwoColumnFieldManager( Display.getWidth() / 2, USE_ALL_WIDTH );
		tcfm_pantalla.setBorder( BorderFactory.createBitmapBorder( new XYEdges( 10, 10, 10, 10 ), 
				Bitmap.getBitmapResource( "border_simple_white.png" ) ) );
		tcfm_pantalla.setMargin( 10, 10, 10, 10 );
		tcfm_pantalla.setPadding( 6, 6, 6, 6 );*/
		
        tcfm_monto = new TwoColumnFieldManager( Display.getWidth() / 3, USE_ALL_WIDTH );
        tcfm_monto.setBorder( BorderFactory.createBitmapBorder( new XYEdges( 10, 10, 10, 10 ), 
        		Bitmap.getBitmapResource( "border_simple_white.png" ) ) );
        tcfm_monto.setPadding( 1, 0, 1, 0 );

		buttonSet = new ListStyleButtonSetScrollManager();
		buttonSet.setScreen(this);
		
		float monto = 0;
		if (lista_articulo.cantElementListaArticulo() > 0)
		{
			pintarListaArticuloCarrito();
			monto = CarritoCompraCache.getInstance().getCostoCarrito();
		}
		else
		{
			pintarVacio();
		}
		this.pintarMonto();
		
		Field separator = new SeparatorField();
		separator.setMargin( 0 , 0 , 0 , 0 );
		separator.setPadding( 0 , 0 , 0 , 0 );
		
		/*tcfm_pantalla.add(tcfm_monto);
		tcfm_pantalla.add(separator);
		tcfm_pantalla.add(buttonSet);
		_foreground.add(tcfm_pantalla);*/
		_foreground.add(tcfm_monto);
		_foreground.add(separator);
		_foreground.add(buttonSet);
		add( _foreground );
	}
	
	public void pintarMonto()
	{
		tcfm_monto.deleteAll();
		lblMontoCarrito = new LabelField("Monto(BsF.): "
				+CarritoCompraCache.getInstance().getCostoCarrito(), USE_ALL_WIDTH | FIELD_HCENTER);

		tcfm_monto.add(lblMontoCarrito);
	}
	
	public void pintarListaArticuloCarrito()
	{
	
		showListField();
		//tcfm_lista_articulo.add(buttonSet);
		//tcfm_lista_articulo.add(buttonSet);
		
	}
	
	public void pintarVacio()
	{
		//tcfm_pantalla.deleteAll();
		buttonSet.deleteAll();
		lblVacio = new LabelField("<< VACIO >>", USE_ALL_WIDTH | 
				DrawStyle.HCENTER |
				DrawStyle.VCENTER );
		buttonSet.add(lblVacio);
	}
	
	public void showListField()
	{
		buttonSet.deleteAll();
		ArticuloCarritoListButtonField link;
		
		for(int i = 0; i < this.lista_articulo.cantElementListaArticulo() ; i++) 
		{
			
			link = new ArticuloCarritoListButtonField(lista_articulo.getArticuloCarritoAtIndex(i), LabelField.ELLIPSIS) 
			{
			
				protected void paintBackground( Graphics g )
				{
					  COLOR_BACKGROUND_FOCUS = Constant.COLOR_LIST_FOCUS;
					  COLOR_BACKGROUND_FOCUS_ACTION = Constant.COLOR_FOCUS_NORMAL;

				      if( _drawPosition < 0 ) 
				      {
				          // it's like a list field, let the default background be drawn
				          super.paintBackground( g );
				          return;
				      }
				      
				      int oldColour = g.getColor();
				      
				      int focus = COLOR_BACKGROUND_FOCUS;
				      if(_doAction) 
				    	  focus = COLOR_BACKGROUND_FOCUS_ACTION;
				      
				      int background = g.isDrawingStyleSet( Graphics.DRAWSTYLE_FOCUS ) ? focus : Constant.COLOR_BACKGROUND;
				      try 
				      {
				          if( _drawPosition == 0 ) 
				          {
				              // Top
				              g.setColor( background );
				              g.fillRoundRect( 0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.setColor( COLOR_BORDER );
				              g.drawRoundRect( 0, 0, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.drawLine( 0, getHeight() - 1, getWidth(), getHeight() - 1 );
				          } 
				          else if( _drawPosition == 1 ) 
				          {
				              // Bottom 
				              g.setColor( background );
				              g.fillRoundRect( 0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.setColor( COLOR_BORDER );
				              g.drawRoundRect( 0, -CORNER_RADIUS, getWidth(), getHeight() + CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				          } 
				          else if( _drawPosition == 2 ) 
				          {
				              // Middle
				              g.setColor( background );
				              g.fillRoundRect( 0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.setColor( COLOR_BORDER );
				              g.drawRoundRect( 0, -CORNER_RADIUS, getWidth(), getHeight() + 2 * CORNER_RADIUS, CORNER_RADIUS, CORNER_RADIUS );
				              g.drawLine( 0, getHeight() - 1, getWidth(), getHeight() - 1 );
				          } 
				          else 
				          {
				              // Single
				              g.setColor( background );
				              g.fillRoundRect( 0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS );
				              g.setColor( COLOR_BORDER );
				              g.drawRoundRect( 0, 0, getWidth(), getHeight(), CORNER_RADIUS, CORNER_RADIUS );
				          }
				      } 
				      finally 
				      {
				          g.setColor( oldColour );
				      }
				}
			};
			/*if (i < 4)
			{
				if (lista_articulo.getArticuloCarritoAtIndex(i).getArticulo().getFotoArticulo() == null)
					link.getFotoArticulo();
			}*/
			link.setChangeListener( this );
	        buttonSet.add( link );
		}

	}
	/*public void showListFieldViejo()
	{
		buttonSet.deleteAll();
		LinedGridFieldManager lgfm;
		LabelField lbl_nombre,lbl_cant,lbl_precio;
		
		for(int i = 0; i < lista_articulo.cantElementListaArticulo() ; i++) 
		{
			ArticuloCarrito elArticuloCarrito = lista_articulo.getArticuloCarritoAtIndex(i);
			lgfm = new LinedGridFieldManager(intWidth, 
					FIELD_HCENTER | FIELD_VCENTER | 
					USE_ALL_WIDTH | Field.FOCUSABLE, elArticuloCarrito);
			if (i == 0)
			{
				lgfm.setBorder(elBorder_Inicio);
			}
			else if (i == (lista_articulo.cantElementListaArticulo() - 1))
			{
				lgfm.setBorder(elBorder_Final);
			}
			else
			{
				lgfm.setBorder(elBorder_Medio);
			}
			lbl_cant = new LabelField(String.valueOf(elArticuloCarrito.getCantidadSeleccionada()), 
					DrawStyle.RIGHT | FIELD_VCENTER | FIELD_HCENTER | USE_ALL_WIDTH | USE_ALL_HEIGHT );
			float value_cal = elArticuloCarrito.getArticulo().getPrecioUnitario()*
					elArticuloCarrito.getCantidadSeleccionada();
			Formatter f = new Formatter();
			String str_val = f.formatNumber(value_cal,2);
			lbl_precio = new LabelField(str_val, 
					DrawStyle.RIGHT | FIELD_VCENTER | FIELD_HCENTER | USE_ALL_WIDTH | USE_ALL_HEIGHT );
			
			lbl_nombre = new LabelField(elArticuloCarrito.getArticulo().getNombreArticulo(), 
					DrawStyle.LEFT | FIELD_VCENTER | FIELD_HCENTER | USE_ALL_WIDTH | USE_ALL_HEIGHT );
			lbl_nombre.setMargin(margin);
			lbl_nombre.setPadding(margin);
			lbl_cant.setMargin(margin);
			lbl_cant.setPadding(margin);
			lbl_precio.setMargin(margin);
			lbl_precio.setPadding(margin);
			lgfm.add(lbl_nombre);
			lgfm.add(lbl_cant);
			lgfm.add(lbl_precio);
			lgfm.add(new NullField(Field.FOCUSABLE));
			lgfm.setChangeListener(this);
			buttonSet.add(lgfm);
			//
			//lgfm.add(new NullField());
			
		}
		
	}
	
	public void showListField2()
	{
		buttonSet.deleteAll();
		tcfm_lista_articulo.deleteAll();
		//tcfm_pantalla.deleteAll();
		CustomHorizontalFieldManager link;
		
		for(int i = 0; i < lista_articulo.cantElementListaArticulo() ; i++) 
		{

			link = new CustomHorizontalFieldManager(lista_articulo.getArticuloCarritoAtIndex(i), 
					HorizontalFieldManager.FOCUSABLE | Field.FOCUSABLE | USE_ALL_WIDTH);
			
			if (i == 0)
			{
				link.setBorder(BorderFactory.createSimpleBorder(new XYEdges(2, 1, 1, 2)));
			}
			else if (i == (lista_articulo.cantElementListaArticulo() - 1))
			{
				link.setBorder(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 2, 2)));
			}
			else
			{
				link.setBorder(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 1, 2)));
			}
			link.setChangeListener( this );
	        buttonSet.add( link );

    		
		}
	}
	
	public void showListField1()
	{
		buttonSet.deleteAll();
		tcfm_lista_articulo.deleteAll();
		
		//tcfm_pantalla.deleteAll();
		gfm = new GridFieldManager(lista_articulo.cantElementListaArticulo(), 3, 
				Field.FOCUSABLE | FIELD_HCENTER );
		//gfm.setBorder(elborder_body);
		
		gfm.setColumnProperty(0, GridFieldManager.PREFERRED_SIZE_WITH_MAXIMUM, Display.getWidth()/3);
		gfm.setColumnProperty(1, GridFieldManager.PREFERRED_SIZE_WITH_MAXIMUM, Display.getWidth()/4);
		gfm.setColumnProperty(2, GridFieldManager.PREFERRED_SIZE_WITH_MAXIMUM, Display.getWidth()/3);
		//gfm.setBorder(elborder);
		
		for (int i = 0 ; i < lista_articulo.cantElementListaArticulo() ;  i++ )
		{
			LabelField label_nombre = new LabelField(lista_articulo.getArticuloCarritoAtIndex(i).
					getArticulo().getNombreArticulo(), LabelField.ELLIPSIS);
			LabelField label_cant = new LabelField(""+lista_articulo.getArticuloCarritoAtIndex(i).
					getCantidadSeleccionada(), LabelField.ELLIPSIS);
			LabelField label_precio = new LabelField(""+(lista_articulo.getArticuloCarritoAtIndex(i).
					getArticulo().getPrecioUnitario() * lista_articulo.getArticuloCarritoAtIndex(i).
					getCantidadSeleccionada()), LabelField.ELLIPSIS);
			
			
			gfm.set(label_nombre, i, 0);
			gfm.set(label_cant, i, 1);
			gfm.set(label_precio, i, 2);
			
			
			
		}
		buttonSet.add(gfm);
		
		
	}*/
	
	public void fieldChanged( Field field, int context ) 
	{
		ScreenEngine.getInstance().goDetailsArticuloCarrito(lista_articulo.getArticuloCarritoAtIndex(field.getIndex()));
		
	}	
}


